package com.andnnl.bytes;

import java.util.Arrays;
import java.util.List;

/**
 * Created by chenss on 2023/7/5.
 */
public class IpToIntTest {
    public static void main(String[] args) {

//        String ip = "192.168.1.1";//-1062731519
//        String ip = "110.168.1.1";//1856504065
//        String ip = "255.255.255.255";//-1 4294967295
//        String ip = "255.255.255.254";//-2 4294967295

        List<String> list = Arrays.asList("192.168.1.1", "110.168.1.1", "1.1.1.1", "255.255.255.255");
        for (String ip : list) {
            int rs = convertIPToInt2(ip);
            System.out.println(rs);
            System.out.println(convertIPToInt(ip));
            System.out.println(convertIntToIP(convertIPToInt(ip)));
            System.out.println();
        }
    }

    private static int convertIPToInt2(String ip) {
        String[] ss = ip.split("\\.");
        int rs = 0;
        byte[] bs = new byte[4];
        for (int i = 0; i < ss.length; i++) {
            int s = Integer.parseInt(ss[i]);
//            s = s >= 128 ? (128-s) : s;
//            bs[4 - i - 1] = (byte) (s & 0XFF);
//            System.out.println(s + "->" + bs[4 - i - 1]);
            rs += (s & 0XFF) << ((4 - i - 1) * 8) ;
//            rs += s << (4 - i - 1) * 8;
        }
        return rs;
    }

    public static int convertIPToInt(String ipAddress) {
        String[] ipParts = ipAddress.split("\\.");
        int ipInt = 0;
        for (int i = 0; i < 4; i++) {
            int s = Integer.parseInt(ipParts[i]);
//            s = s >= 128 ? (128-s) : s;
            ipInt = (ipInt << 8) | (s & 0XFF);
//            ipInt = (ipInt << 8) + (s & 0XFF);
        }
        return ipInt;
    }

    public static String convertIntToIP(int ipInt) {
        StringBuilder ipAddress = new StringBuilder();
        for (int i = 3; i >= 0; i--) {
            int octet = (ipInt >> (i * 8)) & 0xFF;
            if (i < 3) {
                ipAddress.append(".");
            }
            ipAddress.append(octet);
        }
        return ipAddress.toString();
    }

    public static int convertIntToIP2(int ip) {
        String rs = "";
        rs += ip >> 24;
        rs += ".";
        rs += ip >> 16 & 0x000000ff;
        rs += ".";
        rs += ip >> 8 & 0x000000ff;
        rs += ".";
        int ipInt = 0;

        return ipInt;
    }
}
